<?php

namespace App\Models\Circle;

use App\Jobs\Circle\UpdateCircleCountJob;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxUserCircle;
use App\Models\User\WxUser;
use App\Models\WxChat;
use App\Models\WxPlate;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Laravel\Scout\Searchable;

class WxCircle extends Model
{
	use HasDateTimeFormatter;
    use SoftDeletes;
    use Searchable;

    protected $table = 'wx_circle';

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            // 在模型创建之前触发的操作
            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANT_ID__ === 0){
                $model->tenant_show = 0;
                $model->tenant_id = 0;
            }else{
                $model->tenant_show = $__MINI_GLOBAL_TENANT_ID__;
                $model->tenant_id = $__MINI_GLOBAL_TENANT_ID__;
            }
            if($model->circle_state == 1){
                if($model->tenant_show == -1){
                    if(WxCircle::where('id', '<>', $model->id)->where('circle_name', $model->circle_name)->where('circle_state', 1)->exists()){
                        throw new \Exception('已经存在相同名称的全站圈子');
                    }
                }else{
                    if(WxCircle::where('id', '<>', $model->id)->where('circle_name', $model->circle_name)->where('tenant_show', -1)->where('circle_state', 1)->exists()){
                        throw new \Exception('已经存在相同名称的全站圈子');
                    }
                    if(WxCircle::where('id', '<>', $model->id)->where('circle_name', $model->circle_name)->where('tenant_show', $model->tenant_show)->where('circle_state', 1)->exists()){
                        throw new \Exception('分站'.$model->tenant_show.'已经存在相同名称的圈子');
                    }
                }
            }
        });

        static::created(function ($model) {

        });

        static::updating(function ($model) {
            $model->original = $model->getOriginal();
            // 在模型更新之前触发的操作
            if($model->circle_state == 1){
                if($model->tenant_show == -1) {
                    if (WxCircle::where('id', '<>', $model->id)->where('circle_name', $model->circle_name)->where('circle_state', 1)->exists()) {
                        throw new \Exception('已经存在相同名称的圈子');
                    }
                }else{
                    if(WxCircle::where('id', '<>', $model->id)->where('circle_name', $model->circle_name)->where('tenant_show', -1)->where('circle_state', 1)->exists()){
                        throw new \Exception('已经存在相同名称的全站圈子');
                    }
                    if (WxCircle::where('id', '<>', $model->id)->where('circle_name', $model->circle_name)->where('tenant_show', $model->tenant_show)->where('circle_state', 1)->exists()) {
                        throw new \Exception('分站'.$model->tenant_show.'已经存在相同名称的圈子');
                    }
                }
            }
        });

        static::updated(function ($model) {
            $original = $model->original;
            $changes = $model->getChanges();
            foreach ($changes as $key => $value) {
                if($key == 'circle_name'){
                    WxPost::withoutSyncingToSearch(function () use (&$model){
                        WxPost::where('circle_id',$model->id)->update([
                            'circle_name' => $model->circle_name,
                        ]);
                    });
                }
                if($key == 'is_tenant_select' || $key == 'tenant_show'){
                    Cache::remember('circle:default:is:tenant:'.$circle_id, 36000, function () use (&$circle_id){
                        $circle = WxCircle::find($circle_id);
                        if($circle){
                            if($circle->tenant_show == -1 && $circle->is_tenant_select == 1){
                                return 1;
                            }
                        }
                        return 0;
                    });
                }
            }
        });

        static::deleted(function ($model) {
            WxChat::where('expand_type', 107)->where('expand_id', $model->id)->forceDelete();
        });

    }

    public function ower()
    {
        return $this->hasOne(WxUser::class, 'id', 'user_id');
    }


    public function searchableAs()
    {
        return str_replace('.', '_', str_replace(['https://', 'http://'], '', env('APP_URL', 'minisns.cn'))).'_'.'circle_wx_circle_index';
    }

    /**
     * 获取模型的可索引的数据。
     *
     * @return array
     */
    public function toSearchableArray()
    {
        $array = $this->toArray();

        $search_data = [
            'id' => $array['id'],
            'circle_name' => $array['circle_name'],
            'circle_introduce' => $array['circle_introduce'],
            'circle_state' => $array['circle_state'],
            'tenant_id' => $array['tenant_id'],
        ];

        return $search_data;
    }
    /**
     * 确定模型是否可搜索
     *
     * @return bool
     */
    public function shouldBeSearchable()
    {
        return ($this->circle_state == 1);
    }

    public function wxPlate()
    {
        return $this->hasOne(WxPlate::class,'id','plate_id');
    }

    public function wxUser()
    {
        return $this->hasOne(WxUser::class,'id','user_id');
    }

    public function wxPosts(){
        return $this->hasMany(WxPost::class,'circle_id','id')->where('is_examine', 1)->where('posts_state', 0);
    }

    /**
     * 限制显示2条
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function posts(){
        return $this->hasMany(WxPost::class,'circle_id','id')->select()->limit(2);
    }

    public function wxUserCircle()
    {
        return $this->hasMany(WxUserCircle::class,'circle_id','id')->where('user_circle_state', 0);
    }

    /**
     * 圈子的用户信息
     */
    public function getCircleUserAttribute()
    {
        return UserUtils::get_cached_user($this->user_id, true);
    }

    /**
     * 圈子的笔记数量
     */
    public function getCirclePostsCountAttribute()
    {
        return (int)(Cache::remember('circle:postCount:'.$this->id, 600, function (){
            $postCount = WxPost::where('circle_id',$this->id)->where('is_examine', 1)->where('posts_state', 0)->count();
            if($postCount != $this->count_circle_posts){
                UpdateCircleCountJob::dispatch($this->id);
            }
            return $postCount;
        }));
    }



    /**
     * 圈子的关注人数
     */
    public function getCircleFollowCountAttribute()
    {
        return (int)(Cache::remember('circle:followCount:'.$this->id, 600, function (){
            $followCount = WxUserCircle::where('circle_id',$this->id)->where('user_circle_state', 0)->count();
            if($followCount != $this->count_circle_follow){
                UpdateCircleCountJob::dispatch($this->id);
            }
            return $followCount;
        }));
    }



}
